//
//  OcrScanViewController.m
//  ICrEAM
//
//  Created by mac on 17/5/8.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "OcrScanViewController.h"
#import "SmartOCR.h"
@interface OcrScanViewController ()<AVCaptureVideoDataOutputSampleBufferDelegate>{
    BOOL _on;//闪光灯是否打开
    SmartOCR *_ocr;//核心
    BOOL _isRecoging;//是否正在识别
    int _currentRecogType;//当前识别的子类型
    NSString *_currentOCRID;//当前识别的子类型代码
    
}
@property (weak, nonatomic) IBOutlet UIView *scanView;
@property (nonatomic, strong) UIImageView *line;//交互线
@property (nonatomic, strong) NSTimer *lineTimer;//交互线控制
@property (assign, nonatomic) BOOL adjustingFocus;//是否正在对焦
@end

@implementation OcrScanViewController
- (void) setROI
{
  /*
    //设置识别区域
    CGRect rect = _scanView.frame;
    CGFloat scale = 1080.0/ScreenWidth; //1080为当前分辨率(1920*1080)中的宽
    int sTop = (CGRectGetMinY(rect))*scale;
    int sBottom = CGRectGetMaxY(rect)*scale;
    int sLeft = CGRectGetMinY(rect)*scale;
    int sRight = (CGRectGetMaxX(rect))*scale;
    CGFloat dValue = (ScreenWidth/1080*1920-ScreenHeight)*scale*0.5;
    
*/
    CGRect rect = CGRectMake(ScreenHeight-CGRectGetMaxY(_scanView.frame), CGRectGetMinX( _scanView.frame), _scanView.frame.size.height,  _scanView.frame.size.width);
    CGFloat scale = 1080.0/ScreenHeight; //1080为当前分辨率(1920*1080)中的宽
    int sTop = (ScreenHeight - CGRectGetMaxX(rect))*scale;
    int sBottom = (ScreenHeight - CGRectGetMinX(rect))*scale;
    int sLeft = CGRectGetMinY(rect)*scale;
    int sRight = (CGRectGetMinY(rect) + CGRectGetHeight(rect))*scale;
    CGFloat dValue = (ScreenHeight/1080*1920-ScreenWidth)*scale*0.5;
   
    [_ocr setROIWithLeft:sLeft+dValue Top:sTop Right:sRight+dValue Bottom:sBottom];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化识别核心
    [self initOCRSource];
    //初始化相机
    [self initialize];
    
    //创建相机界面控件
    
//    self.resultDataSource = [NSMutableArray array];
//    self.fieldDataSource = [NSMutableArray array];
//    for (SubType *subtype in self.subTypes) {
//        
//        [self.resultDataSource addObject:@""];
//        [self.fieldDataSource addObject:@"VIN码"];
//        [self.imagePaths addObject:@""];
//    }
    [self setOverlayPickerView];
    _currentOCRID=@"SV_ID_VIN_CARWINDOW";
    int currentTemplate = [_ocr setCurrentTemplate:_currentOCRID];
    [self setROI];
    NSLog(@"设置模板返回值：%d", currentTemplate);
//    CGRect flashBtnFrame = CGRectMake(CGRectGetMaxX(self.sframe)-54, 28, 30, 30);
//    UIButton *flashBtn = [[UIButton alloc]initWithFrame:flashBtnFrame];
//    [flashBtn setImage:[UIImage imageNamed:@"flash_camera_btn"] forState:UIControlStateNormal];
//    [flashBtn addTarget:self action:@selector(flashBtn) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:flashBtn];

    [self createBackBtn];
        // Do any additional setup after loading the view from its nib.
}
- (void)createBackBtn
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(24, 28, 30, 30)];
    [btn setImage:[UIImage imageNamed:@"back_item"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(cancleSYQRCodeReading) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}
//取消扫描
- (void)cancleSYQRCodeReading
{
    [self stopSYQRCodeReading];
    
    if (self.SYQRCodeCancleBlock)
    {
        self.SYQRCodeCancleBlock(self);
    }
}

- (void)stopSYQRCodeReading
{
    
    if (_lineTimer)
    {
        [_lineTimer invalidate];
        _lineTimer = nil;
    }

    //
    [self.session stopRunning];
    //
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.adjustingFocus = YES;
    _isRecoging = NO;
    
    //隐藏navigationBar
    self.navigationController.navigationBarHidden = YES;
    //定时器 开启连续对焦
    
//    _isTakePicBtnClick = NO;
    AVCaptureDevice*camDevice =[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    int flags = NSKeyValueObservingOptionNew;
    //注册通知
    [camDevice addObserver:self forKeyPath:@"adjustingFocus" options:flags context:nil];
    [self.session startRunning];
}
- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //移除聚焦监听
    AVCaptureDevice*camDevice =[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    [camDevice removeObserver:self forKeyPath:@"adjustingFocus"];
    [self.session stopRunning];
    
}
//监听对焦
-(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context {
    if([keyPath isEqualToString:@"adjustingFocus"]){
        self.adjustingFocus =[[change objectForKey:NSKeyValueChangeNewKey] isEqualToNumber:[NSNumber numberWithInt:1]];
        //对焦中
    }
}
- (void)setOverlayPickerView
{
    //画中间的基准线
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(self.scanView.frame.origin.x, self.scanView.frame.origin.y, self.scanView.frame.size.width, 3)];
    [_line setImage:[UIImage imageNamed:@"img_line"]];
    [self.view addSubview:_line];
        _lineTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 20 target:self selector:@selector(animationLine) userInfo:nil repeats:YES];
    
}

- (void) initOCRSource
{
    //    //初始化核心
    _ocr = [[SmartOCR alloc] init];
    int init = [_ocr initOcrEngineWithDevcode:@"5LIK5RW355SO5YA"];
    NSLog(@"初始化返回值 = %d 核心版本号 = %@", init, [_ocr getVersionNumber]);
    
    //添加模板
    NSString *templateFilePath = [[NSBundle mainBundle] pathForResource:@"SZHY" ofType:@"xml"];
    int addTemplate = [_ocr addTemplateFile:templateFilePath];
    NSLog(@"添加主模板返回值 = %d", addTemplate);
}
//闪光灯按钮点击事件
- (void)flashBtn{
    
    AVCaptureDevice *device = [self cameraWithPosition:AVCaptureDevicePositionBack];
    if (![device hasTorch]) {
        //        NSLog(@"no torch");
    }else{
        [device lockForConfiguration:nil];
        if (!_on) {
            [device setTorchMode: AVCaptureTorchModeOn];
            _on = YES;
        }
        else
        {
            [device setTorchMode: AVCaptureTorchModeOff];
            _on = NO;
        }
        [device unlockForConfiguration];
    }
}
//获取摄像头位置
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices)
    {
        if (device.position == position)
        {
            return device;
        }
    }
    return nil;
}


#pragma mark - 初始化识别核心
//初始化相机
- (void) initialize
{
    //判断摄像头授权
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        
        UIAlertView * alt = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"allowCamare", nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alt show];
        return;
    }
    
    //1.创建会话层
    self.session = [[AVCaptureSession alloc] init];
    //设置图片品质，此分辨率为最佳识别分辨率，建议不要改动
    [self.session setSessionPreset:AVCaptureSessionPreset1920x1080];
    
    //2.创建、配置输入设备
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    
    for (AVCaptureDevice *device in devices)
    {
        if (device.position == AVCaptureDevicePositionBack)
        {
            self.captureInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
        }
    }
    [self.session addInput:self.captureInput];
    
    ///创建、配置预览输出设备
    AVCaptureVideoDataOutput *captureOutput = [[AVCaptureVideoDataOutput alloc] init];
    captureOutput.alwaysDiscardsLateVideoFrames = YES;
    
    dispatch_queue_t queue;
    queue = dispatch_queue_create("cameraQueue", NULL);
    [captureOutput setSampleBufferDelegate:self queue:queue];
    
    NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey;
    NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
    NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key];
    [captureOutput setVideoSettings:videoSettings];
    
    [self.session addOutput:captureOutput];
    
    //3.创建、配置输出
    self.captureOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil];
    [self.captureOutput setOutputSettings:outputSettings];
    [self.session addOutput:self.captureOutput];
    
    //设置预览
    self.preview = [AVCaptureVideoPreviewLayer layerWithSession: self.session];
    self.preview.frame =CGRectMake(0, 68, self.sframe.size.width, self.sframe.size.height-68);
    self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.preview.connection.videoOrientation = AVCaptureVideoOrientationLandscapeRight|AVCaptureVideoOrientationLandscapeLeft;
//    [self.view.layer addSublayer:self.preview];
     [self.view.layer insertSublayer:self.preview atIndex:0];
    
    [self.session startRunning];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark 上下滚动交互线

- (void)animationLine
{
    __block CGRect frame = _line.frame;
    
    static BOOL flag = YES;
    
    if (flag)
    {
        frame.origin.y = self.scanView.frame.origin.y;
        flag = NO;
        
        [UIView animateWithDuration:1.0 / 20 animations:^{
            
            frame.origin.y += 5;
            _line.frame = frame;
            
        } completion:nil];
    }
    else
    {
        if (_line.frame.origin.y >= self.scanView.frame.origin.y)
        {
            if (_line.frame.origin.y >= (self.scanView.frame.origin.y+self.scanView.frame.size.height-5))
            {
                frame.origin.y = self.scanView.frame.origin.y;
                _line.frame = frame;
                
                flag = YES;
            }
            else
            {
                [UIView animateWithDuration:1.0 / 20 animations:^{
                    
                    frame.origin.y += 5;
                    _line.frame = frame;
                    
                } completion:nil];
            }
        }
        else
        {
            flag = !flag;
        }
    }
    
}
//从摄像头缓冲区获取图像
#pragma mark - AVCaptureSession delegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
       fromConnection:(AVCaptureConnection *)connection
{
    //获取当前帧数据
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    CVPixelBufferLockBaseAddress(imageBuffer,0);
    uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
    
    int width = (int)CVPixelBufferGetWidth(imageBuffer);
    int height = (int)CVPixelBufferGetHeight(imageBuffer);
    
    if (!_isRecoging) {
        //加载图像
        [_ocr loadStreamBGRA:baseAddress Width:width Height:height];
        //识别
        int recog = [_ocr recognize];
        
   
        if (recog == 0) {
            NSLog(@"_currentRecogType3 = %d", _currentRecogType);
            _isRecoging = YES;
            //识别成功，取结果
            AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            NSString *result = [_ocr getResults];
            
            NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *imagePath = [documents[0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", _currentOCRID]];
            [_ocr saveImage:imagePath];
            
//            self.resultDataSource[_currentRecogType] = result;
            NSLog(@"%d,%@",  _currentRecogType, self.resultDataSource[_currentRecogType]);
            
//            self.imagePaths[_currentRecogType] = imagePath;
//            if (_isTakePicBtnClick) {
//                self.resultDataSource[_currentRecogType] = @" ";
//                _isTakePicBtnClick = NO;
//            }
            NSLog(@"_currentRecogType4 = %d", _currentRecogType);
            
            dispatch_async(dispatch_get_main_queue(), ^{
//                NSString *string = self.resultDataSource[self.resultDataSource.count-1];
                
                if (result.length == 0) {
                    
                    if (_currentRecogType < self.fieldDataSource.count-1) {
            
                    }
                }else{
                    [_session stopRunning];
                    
           
                        //VIN码
                        if (self.SYQRCodeSuncessBlock) {
                            self.SYQRCodeSuncessBlock(self,result);
                        }

                }
            });
        }
        
    }
    
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);
}
//对焦
- (void)fouceMode{
    NSError *error;
    AVCaptureDevice *device = [self cameraWithPosition:AVCaptureDevicePositionBack];
    if ([device isFocusModeSupported:AVCaptureFocusModeAutoFocus])
    {
        if ([device lockForConfiguration:&error]) {
            CGPoint cameraPoint = [self.preview captureDevicePointOfInterestForPoint:self.view.center];
            [device setFocusPointOfInterest:cameraPoint];
            [device setFocusMode:AVCaptureFocusModeAutoFocus];
            [device unlockForConfiguration];
        } else {
            NSLog(@"Error: %@", error);
        }
    }
}

@end
